package com.wu.http.server;

import com.wu.javax.servlet.http.HttpSession;
import com.wu.javax.servlet.http.HttpSessionContext;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: tomcatServer
 * @author: 吴磊
 * @create: 2021-12-31 14:03
 */
public class MyHttpSession implements HttpSession {
    private final Map<String, Object> attributes = new HashMap<>();
    private final long creationTime;
    private final String id;
    private long lastAccessedTime;


    /**
     * 无参的构造方法
     */
    public MyHttpSession() {
        this.id = UUID.randomUUID().toString().replaceAll("-", "");
        this.creationTime = System.currentTimeMillis();
        this.lastAccessedTime = this.creationTime;
        HttpSessionContext instance = MyHttpSessionContext.getInstance();
        instance.setSession(this.id, this);
    }

    @Override
    public Object getAttribute(String name) {
        return attributes.get(name);
    }

    @Override
    public void setAttribute(String name, Object value) {
        attributes.put(name, value);
        this.lastAccessedTime = System.currentTimeMillis();
    }

    @Override
    public void removeAttribute(String name) {
        this.attributes.remove(name);
        this.lastAccessedTime = System.currentTimeMillis();
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public long getCreationTime() {
        return this.creationTime;
    }

    @Override
    public long getLastAccessedTime() {
        return this.lastAccessedTime;
    }

    @Override
    public String toString() {
        return "[attributes=" + attributes + ", id=" + id + "]";
    }
}
